package Multiplayer;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.LinkedList;

import personagens.ObjectoMapa;

import mapa.Mapa;

public class Servidor {
	private ServerSocket server;
	private Socket socket;
	private int porta = 8080;// mudar
	private Mapa mapa;

	private LinkedList<ObjectoMapa> objectosMapa;

	public Servidor() {
		try {
			server = new ServerSocket(porta);
			socket = server.accept();
			OutputStream outSocket = socket.getOutputStream();
			ObjectOutputStream saida = new ObjectOutputStream(outSocket);

			InputStream inSoccket = socket.getInputStream();
			ObjectInputStream entrada = new ObjectInputStream(inSoccket);

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				server.close();
				socket.close();

			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}

	public void enviaDadosParaComputadorRemoto(DadosLigacao dadosDeConexao,
			LinkedList<ObjectoMapa> mapa) {
		try {
			socket = new Socket(dadosDeConexao.getServidor(),
					dadosDeConexao.getPortaRemota());
			OutputStream outSocket = socket.getOutputStream();
			ObjectOutputStream saida = new ObjectOutputStream(outSocket);
			saida.writeObject(mapa);
			saida.close();
			outSocket.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public LinkedList<ObjectoMapa> sincronizaMapa(
			ArrayList<Cliente> listaClientes) {
		LinkedList<ObjectoMapa> aux = new LinkedList<ObjectoMapa>();
		LinkedList<ObjectoMapa> aux2 = new LinkedList<ObjectoMapa>();

		for (Cliente a : listaClientes) {
			aux2 = a.getListaObjectos();
			for (ObjectoMapa o : aux2) {
				aux.add(o);
			}
		}
		return aux;

	}

	public LinkedList<ObjectoMapa> extrairMapa(Socket socket) {
		try {
			InputStream dados = socket.getInputStream();
			ObjectInputStream ois = new ObjectInputStream(dados);
			Object o = ois.readObject();
			LinkedList<ObjectoMapa> mapaRecuperado = (LinkedList<ObjectoMapa>) o;
			return mapaRecuperado;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
}
